package com.situ.personal.controlle;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.personal.dao.AdmLogDao;
import com.situ.personal.entity.LogInfo;
import com.situ.personal.util.MD5Util;

@WebServlet("/admlog")
public class AdmLogServlet extends HttpServlet{
	AdmLogDao admLogDao = new AdmLogDao();
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		if (method == null || method.equals("")) {
			method = "login";
		}
		switch (method) {
		case "login":
			login(req,resp);
			break;
		case "logout":
			logout(req,resp);
			break;

		default:
			break;
		}
	}

	private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		HttpSession session = req.getSession(false);
		if (session != null) {
			req.removeAttribute("logInfo");
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
		}
	}

	private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		System.out.println("AdmLogServlet.login()");
		String checkCode = req.getParameter("checkCode");
		String admName = req.getParameter("name");
		String admPasswordBefore = req.getParameter("password");
		String admPassword = MD5Util.MD5Encode(admPasswordBefore);
		HttpSession session = req.getSession();
		String checkCodeInSession = (String) session.getAttribute("checkCodeInSession");
		if (checkCode == null 
				|| checkCode.equals("")
				|| !checkCodeInSession.equalsIgnoreCase(checkCode)) {
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
			return;
		}
		LogInfo logInfo = admLogDao.login(admName,admPassword);
		System.out.println(logInfo);
		if (logInfo == null) {
			resp.sendRedirect(req.getContextPath() + "/fail.jsp");
			return;
		}
		session.setAttribute("logInfo", logInfo);
		resp.sendRedirect(req.getContextPath() + "/index.jsp");
	}
}
